import OSS from 'ali-oss';
import * as fs from 'fs-extra';
import { CloudServiceInterface, FileInfo, CloudConfig } from '../types';
import { Logger } from '../../utils/Logger';

export class AliyunCloudService implements CloudServiceInterface {
  private oss: OSS;
  private config: CloudConfig;

  constructor(config: CloudConfig) {
    this.config = config;
    this.oss = new OSS({
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.secretAccessKey,
      region: config.region,
      bucket: config.bucket,
      endpoint: config.endpoint
    });
  }

  /**
   * 上传文件
   */
  async uploadFile(
    filePath: string,
    remotePath: string,
    onProgress?: (progress: number) => void
  ): Promise<boolean> {
    try {
      const fileContent = await fs.readFile(filePath);
      
      const result = await this.oss.put(remotePath, fileContent);
      
      // 模拟进度回调
      if (onProgress) {
        onProgress(100);
      }
      
      Logger.info('阿里云上传成功:', result);
      return true;
    } catch (error) {
      console.error('阿里云上传失败:', error);
      throw error;
    }
  }

  /**
   * 列出文件
   */
  async listFiles(remotePath: string): Promise<FileInfo[]> {
    try {
      const files: FileInfo[] = [];
      let continuationToken: string | undefined;
      
      do {
        const result = await this.oss.list({
          prefix: remotePath,
          'max-keys': 1000,
          marker: continuationToken
        }, {});
        
        if (result.objects) {
          result.objects.forEach((item: any) => {
            files.push({
              key: item.name,
              size: item.size,
              lastModified: new Date(item.lastModified),
              etag: item.etag.replace(/"/g, '')
            });
          });
        }
        
        continuationToken = result.nextMarker;
      } while (continuationToken);
      
      return files;
    } catch (error) {
      console.error('阿里云列出文件失败:', error);
      throw error;
    }
  }

  /**
   * 删除文件
   */
  async deleteFile(remotePath: string): Promise<boolean> {
    try {
      const result = await this.oss.delete(remotePath);
      Logger.info('阿里云删除文件成功:', result);
      return true;
    } catch (error) {
      console.error('阿里云删除文件失败:', error);
      throw error;
    }
  }

  /**
   * 测试连接
   */
  async testConnection(): Promise<boolean> {
    try {
      const result = await this.oss.getBucketInfo(this.config.bucket);
      Logger.info('阿里云连接测试成功:', result);
      return true;
    } catch (error) {
      console.error('阿里云连接测试失败:', error);
      return false;
    }
  }

  /**
   * 获取文件URL
   */
  getFileUrl(remotePath: string, expires?: number): string {
    return this.oss.signatureUrl(remotePath, {
      expires: expires || 3600
    });
  }

  /**
   * 批量删除文件
   */
  async deleteMultipleFiles(remotePaths: string[]): Promise<boolean> {
    try {
      await this.oss.deleteMulti(remotePaths);
      return true;
    } catch (error) {
      console.error('阿里云批量删除文件失败:', error);
      return false;
    }
  }

  /**
   * 检查文件是否存在
   */
  async fileExists(remotePath: string): Promise<boolean> {
    try {
      await this.oss.head(remotePath);
      return true;
    } catch (error: any) {
      if (error.code === 'NoSuchKey') {
        return false;
      }
      throw error;
    }
  }
}